import {useRequest} from '@umijs/hooks';
import {Button, Cascader, Form, Input, message, Select, Switch} from 'antd';
import {Store} from 'rc-field-form/lib/interface';
import React, {useEffect, useState,useRef} from 'react';
import {getSecretString} from '../../../utils/encrypt';
import {fetchRequest} from '../../../utils/Request';
import {url} from '../../../utils/url';


const {Option} = Select

export default function AddSchool(props: any) {

  const layout = {
    labelCol: {span: 5},
    wrapperCol: {span: 14},
  };


  const tailLayout = {
    wrapperCol: {offset: 5, span: 14},
  };

  const layouts = {
    labelCol: {span: 5},
    wrapperCol: {span: 14},
  };
  let param=useRef({
    pid:'0',
    selectedOption:[]
  })



  const [form] = Form.useForm();

  const [show, setShow] = useState<boolean>(false)

  const [isAdd, setIsAdd] = useState<boolean>(false)

  const [active, setActive] = useState<boolean>(false)
  const [options, setOptions] = useState([]);
  let pid ='0'
  //添加和修改
  const {loading, data} = useRequest(() => fetchRequest(url.GET_CHOICE_LIST, {}), {

    onSuccess: async (result, params) => {

      if (result.success) {


      } else {
        message.error(result.errorMsg)
      }
    }
  })


  function handleFinish(value: Store) {
    const params = {
      ...value,
      pwd: getSecretString(value.pwd),
      epidemicIsActive: value?.epidemicIsActive ? 1 : 0,
      regionId:  value.regionId[value.regionId.length-1],
      cityId:param.current.pid,
      regionName: param.current.selectedOption.join('/'),

    }
    addInfo.run(params)
  }

  //新增的学校的信息
  async function addInfoRequest(params: Store) {
    // console.log(params)
    try {
      const json = await fetchRequest(url.MODIFY_SCHOOL_INFO, params);
      if (json.success) {
        props.addSuccess();

      } else {
        message.destroy();
        message.error(json.error);
      }

      return json
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const addInfo = useRequest(addInfoRequest, {
    manual: true,
    loadingDelay: 200,
    onSuccess: (result) => {
      console.log(result)
    }
  })

  const onValuesChange = (changedValues: any) => {
    if ("isSendMsgRecord" in changedValues) {
      setShow(changedValues?.isSendMsgRecord)
    }

    if ("isAdd" in changedValues) {
      setIsAdd(changedValues.isAdd)
    }

    if ("epidemicIsActive" in changedValues) {
      setActive(changedValues.epidemicIsActive)
    }

  }


  const getAllAddress = useRequest((params)=>fetchRequest(url.GET_NATIONAL_ADDRESS, params), {
    manual: true,
    loadingDelay: 200,
    onSuccess:(res)=>{
      setOptions(res?.data)

    }
  })

  const loadData=async(selectedOptions:any)=>{
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const {data}=await  getAllAddress.run({
      id:targetOption.id
    })

    targetOption.loading = false;
    targetOption.children=data


    setOptions([...options]);
  }

  const onChange=(value:any, selectedOptions:any)=>{
    if(selectedOptions)
    {
      param.current.selectedOption=selectedOptions?.map((item:any)=>item.name)
      param.current.pid=(selectedOptions[selectedOptions.length-1].pid)
    }

  }
  useEffect(() => {

    getAllAddress.run({id:0})
  }, [])
  const hide = show ? 'shows' : 'hidden'
  const hides = isAdd ? 'shows' : 'hidden'
  const activeHide = active ? 'shows' : 'hidden'

  return (
      <Form {...layout} initialValues={{
        isBlackCardRecord: false,
        isFaceCardRecord: false,
        isFaceNecessary: false,
        isSendMsgRecord: false,
        isShortSendMsgRecord: false,
        isSmartStudentCardRecord: false,
        isWhiteCardRecord: false,
        isAdd: false

      }} form={form} onValuesChange={onValuesChange}
            onFinish={handleFinish}>
        <Form.Item name="collegeName" label="学校名称" rules={[{required: true, message: "必须要填写学校名称!"}]}>
          <Input placeholder="请输入学校名称"/>
        </Form.Item>


        <Form.Item validateTrigger="onBlur" name="collegeTerm" label="所属学段"
                   rules={[{required: true, message: "必须要选择所属学段!"}]}>
          <Select placeholder="请选择所属学段">
            {data?.data?.collegeTerms?.map((item: any) => <Option
                value={item.id} key={item.id}>{item.name}</Option>)}
          </Select>
        </Form.Item>
        <Form.Item validateTrigger="onBlur" name="regionId" label="行政区域"
                   rules={[{required: true, message: "必须要选择行政区域!"}]}>
          <Cascader

              fieldNames= {{ label: 'name', value: 'id'}}
              placeholder="必须要选择行政区域"
              options={options}
              loadData={loadData}
              onChange={onChange}

          />


        </Form.Item>
        <Form.Item validateTrigger="onBlur" name="area" label="所属教育局"
                   rules={[{required: true, message: "必须要选择所属教育局!"}]}>
          <Select placeholder="请选择所属教育局">
            {data?.data?.educationAreas?.map((item: any) => <Option
                value={item.id} key={item.id}>{item.educationArea}</Option>)}
          </Select>
        </Form.Item>


        <Form.Item validateTrigger="onBlur" name="college_type" label="办公性质"
                   rules={[{required: true, message: "必须要选择办公性质!"}]}>
          <Select placeholder="请选择办公性质">
            <Option value={1}>公办</Option>
            <Option value={2}>民办</Option>
          </Select>
        </Form.Item>


        <Form.Item name="addrDesc" label="学校地址" rules={[{required: true, message: "必须要填写学校地址!"}]}>
          <Input placeholder="请输入学校地址"/>
        </Form.Item>

        <Form.Item validateTrigger="onBlur" name="locationCode" label="场所码" {...layouts}

        >
          <Input placeholder="请输入场所码"/>
        </Form.Item>

        {/*<Form.Item name="PropManageCom" label="是否物业" valuePropName="checked" rules={[{ required: true, message: "必须要选择是否物业公司!" }]}>*/}
        {/*    <Switch />*/}
        {/*</Form.Item>*/}
        <Form.Item name="isAdd" label="是否添加管理员" valuePropName="checked"
        >
          <Switch/>
        </Form.Item>


        <Form.Item name="contact" label="管理人姓名" {...layouts} className={hides}>
          <Input placeholder="请输入管理人姓名"/>
        </Form.Item>


        <Form.Item validateTrigger="onBlur" name="contactPhone" label="管理人电话" {...layouts} className={hides}
                   rules={[{
                     pattern: /^1[3456789]\d{9}$/,
                     message: '手机号码格式错误！'
                   }]}>
          <Input placeholder="请输入手机号码"/>
        </Form.Item>

        <Form.Item name="pwd" label="登录密码" {...layouts} className={hides} rules={[{
          pattern: /^.*(?=.{8,16})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*?\(\)+=\[\]\{\}_<>,.;:'"-]).*$/,
          message: '密码必须包含数字，字母和特殊字符,至少为8位！'
        }]}>
          <Input.Password placeholder="请输入密码"/>
        </Form.Item>


        {/*<Form.Item name="isFaceNecessary" label="是否人脸必须" valuePropName="checked"*/}
        {/*>*/}
        {/*    <Switch/>*/}
        {/*</Form.Item>*/}

        <Form.Item name="isSendMsgRecord" label="出入是否发送信息" valuePropName="checked"
        >
          <Switch/>
        </Form.Item>


        <Form.Item name="isWhiteCardRecord" label="白卡" valuePropName="checked"
                   className={`  ${hide}    `}{...layouts}>
          <Switch/>
        </Form.Item>

        <Form.Item name="isSmartStudentCardRecord" label="智能学生证"
                   className={` ${hide}    `}{...layouts}
                   valuePropName="checked">
          <Switch/>
        </Form.Item>
        <Form.Item name="isBlackCardRecord" label="黑卡" className={`  ${hide}    `}{...layouts}
                   valuePropName="checked">
          <Switch/>
        </Form.Item>
        <Form.Item name="isFaceCardRecord" label="人脸" className={`  ${hide}    `}{...layouts}
                   valuePropName="checked">
          <Switch/>
        </Form.Item>
        <Form.Item name="isShortSendMsgRecord" label="是否发短信" className={`  ${hide}    `} {...layouts}
                   valuePropName="checked">
          <Switch/>
        </Form.Item>


        <Form.Item name="epidemicIsActive" label="是否添加防疫管理员" valuePropName="checked"
        >
          <Switch/>
        </Form.Item>


        <Form.Item name="epidemicContactName" label="防疫管理人姓名" {...layouts} className={activeHide}>
          <Input placeholder="请输入防疫管理人姓名"/>
        </Form.Item>


        <Form.Item validateTrigger="onBlur" name="epidemicContactPhone" label="防疫管理人电话" {...layouts}
                   className={activeHide}
                   rules={[{
                     pattern: /^1[3456789]\d{9}$/,
                     message: '手机号码格式错误！'
                   }]}>
          <Input placeholder="请输入手机号码"/>
        </Form.Item>


        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit" loading={addInfo.loading}>提交</Button>
        </Form.Item>


      </Form>
  )
}
